<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
     <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>权限管理</el-breadcrumb-item>
     <el-breadcrumb-item>角色列表</el-breadcrumb-item>
     </el-breadcrumb>
    <!-- 列表展示 -->
    <el-card>
     <el-row>
        <el-button type='primary' @click="addrolesfrom=true">添加角色</el-button>
     </el-row>
     <el-row :class="['toprow']">
       <el-table stripe  border :data='roleslist' style="width:100%">
         <el-table-column type='expand'>
           <template slot-scope="scope"> 
             <el-row v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="['bottomborder',index1===0 ? 'topborder':'' ,'flex']">
                <!-- 一级权限 -->
               <el-col :span='5'><el-tag closable  @close='closetag(scope.row,item1.id)'>
                 {{item1.authName}}
                </el-tag >
                 <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二、三 级权限 -->
               <el-col :span='19'>
               <el-row v-for="(item2,index2) in item1.children" :key="item2.id"  :class="[index2===0 ? '':'topborder','flex']">
                   <el-col :span='6' >
                   <el-tag closable type="success"  @close='closetag(scope.row,item2.id)'>{{item2.authName}}</el-tag>
                     <i class="el-icon-caret-right"></i>
                 </el-col>
                 <el-col :span='18'>
                   <el-tag closable v-for="item3 in item2.children" :key="item3.id" type="warning"  @close='closetag(scope.row,item3.id)'>{{item3.authName}}</el-tag>
                 </el-col>
               </el-row>
               </el-col>
             </el-row>
           </template>
         </el-table-column>
         <el-table-column type='index' label='#' width='60' ></el-table-column>
         <el-table-column prop='roleName' label='角色名称'></el-table-column>
         <el-table-column prop='roleDesc' label='角色描述'></el-table-column>
         <el-table-column prop='roleName' label='操作'>
           <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size='small' @click="editroles(scope.row)">编辑</el-button>
                 <el-button type="danger" icon="el-icon-delete"  size='small'  @click='removerole(scope.row)'>删除</el-button>
                   <el-button type="warning" icon="el-icon-s-tools" size='small' @click="getrolesallotlist(scope.row)" >角色分配</el-button>
           </template>
         </el-table-column>
       </el-table>
     </el-row>
    </el-card>
    <!-- 添加角色对话框 -->
  <el-dialog
  title="添加角色信息"
  :visible.sync="addrolesfrom"
  width="50%"
  @close='clearninfo'>
  <el-form :model='rolesinfo' width='80%' :rules="rules" ref="addrolesfrompost">
    <el-form-item label='角色名称'  label-width='80px'  prop='roleName'>
      <el-input  v-model="rolesinfo.roleName" ></el-input>
    </el-form-item>
    <el-form-item label='角色描述' label-width='80px' prop='roleDesc'>
      <el-input  v-model="rolesinfo.roleDesc"></el-input>
    </el-form-item>
  </el-form>
   <span slot="footer" class="dialog-footer">
    <el-button @click="addrolesfrom = false">取 消</el-button>
    <el-button type="primary" @click="addroles" >确 定</el-button>
    </span>
</el-dialog>
<!-- 编辑角色 -->
  <el-dialog
  title="修改角色信息"
  :visible.sync="editrolesfrom"
  width="50%">
  <el-form :model='editfrom' width='80%' :rules="rules" ref="addrolesfrompost">
    <el-form-item label='角色名称'  label-width='80px'  prop='roleName'>
      <el-input  v-model="editfrom.roleName" ></el-input>
    </el-form-item>
    <el-form-item label='角色描述' label-width='80px' prop='roleDesc'>
      <el-input  v-model="editfrom.roleDesc"></el-input>
    </el-form-item>
  </el-form>
   <span slot="footer" class="dialog-footer">
    <el-button @click="editrolesfrom = false">取 消</el-button>
    <el-button type="primary" @click="posteditroles" >确 定</el-button>
    </span>
</el-dialog>
<!-- 角色分配 -->
<el-dialog
  title="角色分配"
  :visible.sync="getrolesshowlist"
  width="50%"
  @close='clearnroles'>
  <el-tree :data="getroleslist" :props="getroleslistprops" show-checkbox default-expand-all node-key='id'
   :default-checked-keys='defkeys'
   ref="tree"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="getrolesshowlist = false">取 消</el-button>
    <el-button type="primary" @click="stoprolesfrom">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
  export default {
    name:'roles',
    data () {
      return {
        roleslist:[],
        addrolesfrom:false,
        editrolesfrom:false,
        getrolesshowlist:false,
        rolesinfo:{
            roleName:'',
            roleDesc:''
        },
        rules:{
          rolename:[
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          roledesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ]
        },
        editfrom:{},
        getroleslist:[],
        getroleslistprops:{
          label:'authName',
          children:'children'
        },
        defkeys:[],
        //分配角色的id
        rolesid:''
      }
    },
    created () {
     this.getRoleslist()
    },
    methods: {
      async getRoleslist(){
        let result= await this.$http.get('roles')
        if(result.data.meta.status !=200) {return this.$message({showClose: true,message: `获取角色列表失败`,type: 'error'}) }
        
        this.roleslist=result.data.data
      },
     async removerole(userinfo){
        let comfigResult= await this.$MessageBox('此操作将永久删除该用户的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
         if(comfigResult !='confirm'){
         return  this.$message('取消删除成功！');
       }
        let result=await this.$http.delete(`roles/${userinfo.id}`)
        if(result.data.meta.status !=200){
          return this.$message({showClose: true,message: `删除用户失败！`,type: 'error'})
        }
       this.$message({showClose: true,message: '删除用户成功！',type: 'success'}); 
      this.getRoleslist()
      },
      //提交添加角色信息
     async addroles(){
       console.log(this.$refs)
     let validate = await this.$refs.addrolesfrompost.validate()
     if(!validate) return
     let result=await this.$http.post('roles',this.rolesinfo)
     console.log(result)
     if(result.data.meta.status !=201) {return this.$message({showClose: true,message: `${result.data.meta.msg}`,type: 'error'}) }
       this.$message({showClose: true,message: `添加新用户成功`,type: 'success'})
       this.getRoleslist()
       this.addrolesfrom = false
      },
    //清楚添加表单信息
     clearninfo(){
      this.$refs.addrolesfrompost.resetFields()
     }, 
    //查找编辑角色信息
    async editroles(userinfo){
      let result =await this.$http.get(`roles/${userinfo.id}`)
      this.editfrom=result.data.data
      this.editrolesfrom=true
    },
    //修改列表信息
    async posteditroles(){
       let result =await this.$http.put(`roles/${this.editfrom.roleId}`,{roleName:this.editfrom.roleName,roleDesc:this.editfrom.roleDesc})
       if(result.data.meta.status !=200){return this.$message({showClose: true,message: `修改用户信息失败`,type: 'error'})}
        this.$message({showClose: true,message: `修改用户信息成功`,type: 'success'})
       this.getRoleslist()
       this.editrolesfrom=false
    },
    //关闭tag提示框
   async  closetag(scope,item){
        let comfigResult= await this.$MessageBox('此操作将永久删除该用户的权限标签, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
         if(comfigResult !='confirm'){
         return  this.$message('取消删除成功！');
       }
        let result=await this.$http.delete(`roles/${scope.id}/rights/${item}`)
        if(result.data.meta.status !=200){
          return this.$message({showClose: true,message: `删除用户权限标签失败！`,type: 'error'})
        }
         this.$message({showClose: true,message: `删除用户权限标签成功！`,type: 'success'})
         scope.children=result.data.data
    },
    //角色分配
    async  getrolesallotlist(scope){
    this.rolesid=scope.id
     let result=await this.$http.get('rights/tree')
     if(result.data.meta.status !=200){return  this.$message({showClose: true,message: `获取分配角色数据失败！`,type: 'error'})}
     this.getroleslist=result.data.data
    this.getrolesshowlist=true
    this.getLeafKey(scope,this.defkeys)
    },
    //递归的方式来获取三级节点
    getLeafKey(node,arr){
      if(!node.children){
       return  arr.push(node.id)
      }
     node.children.forEach(item=>{
       this.getLeafKey(item,arr)
     })
    },
    //清楚分配列表的数据
    clearnroles(){
      this.defkeys=[]
    },
    //提交权限分配
   async stoprolesfrom(){
  const rolesarr=[
    ...this.$refs.tree.getCheckedKeys(),
    ...this.$refs.tree.getHalfCheckedKeys()
  ]
  const strRoles=rolesarr.join(',')
  const result=await this.$http.post(`roles/${this.rolesid}/rights`,{rids:strRoles})
  if(result.data.meta.status !==200){return this.$message({showClose: true,message: `分配角色权限失败！`,type: 'error'})}
   this.$message({showClose: true,message: `分配角色权限成功！`,type: 'success'})
   this.getRoleslist()
   this.getrolesshowlist=false
   }
    }
  }
</script>

<style lang="less" scoped>
 .el-card{
   margin: 15px 0;
 }
 .toprow{
   margin-top: 10px;
 }
 .topborder{
   border-top: 1px solid rgba(0,0,0,.1);
 }
 .bottomborder{
   border-bottom: 1px solid rgba(0,0,0,.1);
 }
 .el-tag{
   margin: 7px;
 }
 .flex{
   display: flex;
   align-items: center;
 }
</style>